require 'rubygems'
require File.join(File.dirname(__FILE__),'lpm.rb')
require File.join(File.dirname(__FILE__),'utils.rb')

begin
  gem 'sinatra'
  require 'sinatra/base'
  require 'activesupport' unless ({}.respond_to? :to_json)
rescue LoadError => e
  p <<DOC
-----------------------------------------------------------------------
LPM say:
The LPM server require sinatra and activesupport.
Please exec "gem install sinatra" or "gem install activesupport" first.
-----------------------------------------------------------------------
Ruby say:
#{e}
-----------------------------------------------------------------------
DOC
  exit(-1)
end

$LPMPool = {}

class AppServer < Sinatra::Base
    get '/' do
      "{\"msg\":\"Welcome using LPM(Linux Proc Monitor)\"}"
    end

    get '/lpm/:verbose' do
      r = ''
      case params[:verbose]
      when /ver/i
        r = "0.1.2";break;
      when /proc/i
        redirect '/proc'
      when /process/i
        redirect '/process'
      end
      r
    end

    get '/proc/:method/*' do
      if params[:method] == nil then
        "Monitor target is needed,such as <a href='/proc/cpuinfo'>/proc/cpuinfo</a>"
      else
        (LPM::Proc.send params[:method],*(params[:splat].split('/'))).to_json
      end
    end

    get '/process/:pid/:method/*' do
      if params[:method] != nil and params[:pid].to_i >= 0 then
        begin
          a_lpm = $LPMPool[params[:pid]]||($LPMPool[params[:pid]] = LPM::Process.new(params[:pid]))
          (a_lpm.send params[:method],*(params[:splat].split('/'))).to_json
        rescue NoPidExist => e
          %Q-{"success":false,"msg":#{e}}-
        end
      else
        "Monitor target and pid is needed,such as <a href='/process/909/status'>/proc/cpuinfo</a>"
      end
    end
end

class LPMServer
  def self.run(host='0.0.0.0',port=9876)
    # Daemon.start{AppServer.run! :host => host, :port => port}
    AppServer.run! :host => host, :port => port
  end
end